<template>
    <div>
        <el-dialog :title="'线上沟通-' + name" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
            <div class="onlineList">
                <ul v-if="type == '0'">
                    <!-- 客服视角 -->
                    <li class="leftChat" v-for="item in onlineData" :key="item.id">
                        <!-- 左边 -->
                        <div class="onlineLeft" v-if="item.roleType == '0'">
                            <img width="30" height="30" src="@/assets/images/userImg2.png" alt="">
                            <!-- 文字 -->
                            <p v-if="item.newsType=='0'" class="onlineRight">{{ item.messageContent }}</p>
                            <!-- 附件 -->
                            <p v-if="item.newsType=='2'" class="onlineRight">
                                <span>{{item.fileName}}</span>
                                <span @click="handleDown(item.messageContent)" class="changeColor">下载</span>
                            </p>
                        </div>
                        <!-- 右边 -->
                        <div class="onlineNew" v-if="item.roleType == '1'">
                            <!-- 文字 -->
                            <p v-if="item.newsType=='0'" class="onlineRight">{{ item.messageContent }}</p>
                            <!-- 附件 -->
                            <p v-if="item.newsType=='2'" class="onlineRight">
                                <span>{{item.fileName}}</span>
                                <span @click="handleDown(item.messageContent)" class="changeColor">下载</span>
                            </p>
                            <img width="35" height="30" src="@/assets/images/kefu.png" alt="">
                        </div>
                    </li>

                </ul>
                <ul v-else>
                    <!-- 用户视角 -->
                    <li class="leftChat" v-for="(item, index) in onlineData" :key="item.id">
                        <!-- 左边 -->
                        <div class="onlineLeft" v-if="item.roleType == '1'">
                            <img width="35" height="30" src="@/assets/images/kefu.png" alt="">
                            <!-- 文字 -->
                            <p v-if="item.newsType=='0'" class="onlineRight">{{ item.messageContent }}</p>
                            <!-- 附件 -->
                            <p v-if="item.newsType=='2'" class="onlineRight">
                                <span>{{item.fileName}}</span>
                                <span @click="handleDown(item.messageContent)" class="changeColor">下载</span>
                            </p>
                        </div>
                        <!-- 右边 -->
                        <div class="onlineNew" v-if="item.roleType == '0'">
                            <!-- 文字 -->
                            <p v-if="item.newsType=='0'" class="onlineRight">{{ item.messageContent }}</p>
                            <!-- 附件 -->
                            <p v-if="item.newsType=='2'" class="onlineRight">
                                <span>{{item.fileName}}</span>
                                <span @click="handleDown(item.messageContent)" class="changeColor">下载</span>
                            </p>
                            <img width="30" height="30" src="@/assets/images/userImg2.png" alt="">
                        </div>
                    </li>
                </ul>
            </div>
            <span slot="footer" class="dialog-footer">
                <div class="iconWrapper">
                    <span>
                        <el-upload :action="imageUploadUrl" name="file" :on-success="handleAvatarSuccess" :limit="1"
                            :on-error="handleError" :file-list="fileList">
                            <i class="el-icon-paperclip"></i><span>上传文件</span>
                        </el-upload>
                    </span>
                </div>

                <div class="footWrapper">
                    <el-input @keyup.enter.native="handleSend" @submit.native.prevent v-model="form.messageContent"
                        placeholder="请输入内容" clearable></el-input>
                    <el-button type="primary" :loading="loading" @click="handleSend()"
                        icon="el-icon-s-promotion">发送</el-button>
                </div>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { chatRoomList, chatSend } from '@/request/api/resource.js'
export default {
    data() {
        return {
            dialogVisible: false,
            input: "",
            onlineData: [],
            userInfo: {},
            params: {
                resourceId: '',//资源id
                userId: '',//用户id
                chatRoomId: null,//聊天室id
                publishId: '',//资源发布者id
            },
            form: {
                resourceId: "", //资源id
                chatRoomId: "", //聊天室id
                fileName: '',//文件名称
                messageContent: "", //消息内容
                newsType: "0" //消息类型（0文字 1图片 2文件）
            },
            type: '',//类型：0发布者；1咨询者
            name: '',//当前用户昵称
            loading: false,
            imageUploadUrl: '/dev-api/file/upload/uploadNotQR',
            fileList: []
        }
    },
    methods: {
        // 定义将滚动条定位在底部的方法
        scrollToBottom() {
            this.$nextTick(() => {
                let chat = this.$el.querySelector(".onlineList")
                chat.scrollTop = chat.scrollHeight
            })
        },
        open(data) {
            console.log(data)
            this.dialogVisible = true
            this.form.messageContent = ''
            this.params.resourceId = data.resourceId
            // this.params.userId = data.userId
            this.form.resourceId = data.resourceId
            this.params.chatRoomId = data.roomId
            this.form.chatRoomId = data.roomId
            this.params.publishId = data.publishId
            this.name = data.name
            this.type = data.type
            if (data.isChat == false) {
                this.onlineData = []
            } else {
                // this.updateTime()
                this.getList()
            }
            this.updateTime()

        },
        updateTime() {
            if (this.dialogVisible) {
                const timer = setInterval(() => {
                    this.getList()
                }, 60000); // 每分钟更新一次时间 
            }
            // const timer = setInterval(() => {
            //     this.getList()
            // }, 60000); // 每分钟更新一次时间  
        },
        // 获取聊天室列表
        getList() {
            chatRoomList(this.params).then(res => {
                if (res.data.code == 200) {
                    this.onlineData = res.data.result
                }
            })
        },
        // 发送消息
        handleSend() {
            if (!this.form.messageContent) {
                this.$message({
                    message: '请输入内容',
                    type: 'warning'
                });
                return false;
            }
            this.loading = true
            chatSend(this.form).then((res) => {
                this.loading = false
                if (res.data.code === 200) {
                    this.$message({
                        message: res.data.message,
                        type: "success",
                    });
                    this.form.chatRoomId = res.data.result
                    this.params.chatRoomId = res.data.result
                    this.form.messageContent = ''
                    this.fileList=[]
                    this.form.fileName = ''
                    this.form.newsType= "0" //消息类型（0文字 1图片 2文件）
                    this.getList()
                    
                } else {
                    this.$message.error(res.data.message);
                }
            });
        },
        // 关闭弹框前提示
        handleClose() {
            this.dialogVisible = false
        },
        handleAllClose() {
            this.dialogVisible = false
            this.onlineData = []
            this.input = ""
        },
        // 上传文件成功
        handleAvatarSuccess(response, file) {
            if (response.code == 200) {
                this.form.fileName = file.name
                this.form.messageContent = response.message
                this.form.newsType = '2'
                this.handleSend()
            } else {
                this.$message({
                    message: response.message,
                    type: "error",
                });
            }
        },
        // 上传文件失败
        handleError(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因:${errInfo.message}`);
        },
        // 下载
        handleDown(url){
            window.open(url)
        }
    }
}
</script>
<style lang="less" scoped>
@import './onlineList.less';
.changeColor{
    color:#409eff;
    font-size:13px;
    margin-left:10px;
    cursor: pointer;
}
</style>
